package com.linkage.seapeak.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.bean.NoticeInfo;
import com.linkage.jz.bankruptcy.fragment.MsgFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.seapeak.base.BaseFragment;
import com.linkage.seapeak.net.ResultCallBack;
import com.linkage.seapeak.pojo.MessageBundle;
import com.linkage.seapeak.pojo.MessageItem;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BaseNoticeFragment extends BaseFragment {

    /**
     * 发送消息
     */
    public void getMsgList(int msgType, String projectId, final ResultCallBack<MessageBundle> callBack) {
        getMsgList(1, 50, msgType, projectId, callBack);
    }
    public void getMsgList(int pageNum, int pageSize, int msgType, String projectId, final ResultCallBack<MessageBundle> callBack) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            Log.i("BaseNoticeFragment", "getMsgList: token为空");
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if("".equalsIgnoreCase(userToken))
        {
            return;
        }
        Network.getAPIService()
                .getMsgList(userToken, projectId, msgType, pageNum, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {

                            if  (json.get("code").getAsInt() == -10004 || (json.get("code").getAsInt() == -10003))
                            {


                                getActivity().runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {

                                        LoginNoticeDialog.showPage(json.get("msg").getAsString());
                                        callBack.onFailed("获取失败");
                                    }


                                });

                                return;
                            }
                            if (json.get("code").getAsInt() == 0) {
                                ArrayList<MessageItem> mData = new ArrayList<>();
                                JsonObject jsondata = json.getAsJsonObject("data");
                                JsonArray ary = jsondata.getAsJsonArray("list");
                                int count = jsondata.get("totalCount").getAsInt();
                                for (int i = 0; i < ary.size(); i++) {
                                    String data = ary.get(i).toString();
                                    MessageItem model = new Gson().fromJson(data, MessageItem.class);
                                    if (!TextUtils.isEmpty(model.getActionParams())) {
                                        MessageItem.ActionParms actionParms = new Gson().fromJson(model.getActionParams().replace("\\", "")
                                                , MessageItem.ActionParms.class);
                                        model.setActionParms(actionParms);
                                    }
                                    String time = Utils.timeStamp2Date(((long) model.getOpAt()) * 1000L, "yyyy-MM-dd HH:mm:ss");
                                    model.setSendTime(time);
                                    mData.add(model);
                                }

                                MessageBundle bundle = new MessageBundle();
                                bundle.setMessageItems(mData);
                                bundle.setCount(count);

                                if (callBack != null)
                                    callBack.onSuccess(bundle);
                            } else {
                                if (callBack != null)
                                    callBack.onFailed("获取失败");
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            if (callBack != null)
                                callBack.onFailed("获取失败");
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (callBack != null)
                            callBack.onFailed("获取失败");
                    }
                });
    }

    /**
     * 已读消息
     */
    public void readone(String msgId, final ResultCallBack<String> callBack) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            Log.i("BaseNoticeFragment", "readone: token为空");
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .readone(userToken, msgId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            if (json.get("code").getAsInt() == 0) {
                                if (callBack != null)
                                    callBack.onSuccess("请求成功");
                            } else {
                                if (callBack != null)
                                    callBack.onFailed("请求失败");
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            if (callBack != null)
                                callBack.onFailed("请求失败");
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (callBack != null)
                            callBack.onFailed("请求失败");
                    }
                });
    }

    public void checkItems() {}

    /**
     * 删除消息
     */
    public void deleteMsg(String msgId, final ResultCallBack<String> callBack) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            Log.i("BaseNoticeFragment", "deleteMsg: token为空");
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .deleteMsg(userToken, msgId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            if (json.get("code").getAsInt() == 0) {
                                if (callBack != null) {
                                    callBack.onSuccess("请求成功");
                                }
                            } else {
                                if (callBack != null)
                                    callBack.onFailed("请求失败");
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            if (callBack != null)
                                callBack.onFailed("请求失败");
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (callBack != null)
                            callBack.onFailed("请求失败");
                    }
                });
    }
}
